package cn.yj.syslog.service;

import cn.yj.common.AppExecutor;
import cn.yj.common.baseDao.ServiceImpl;
import cn.yj.common.lock.reentrant.SyncLocalIVariableLock;
import cn.yj.commons.utils.StringUtils;
import cn.yj.params.check.annotation.Require;
import cn.yj.syslog.entity.SysLog;
import cn.yj.syslog.mapper.SysLogMapper;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-12-17 18:32
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements ISysLogService {
    @Override
    public long countByDate(Date date) {
        return baseMapper.countVisitByDate(date);
    }

    @Override
    public int updateResult(String result, @Require String id) {
        return baseMapper.updateResult(result, id);
    }

    private SyncLocalIVariableLock LOCK=new SyncLocalIVariableLock();

    @Override
    public boolean insertOrUpdate(SysLog t) {
        AppExecutor.exec(()->{
            try {
                // 加锁，解决同一条日志异步处理问题
                LOCK.lock(t.getId());
                if (StringUtils.isNull(baseMapper.selectById(t.getId()))) {
                    baseMapper.insert(t);
                }
                baseMapper.updateById(t);
            } finally {
                LOCK.unlock(t.getId());
            }
        });
        return true;
    }

    @Override
    public long countByDateRange(Date startTime, Date endTime) {
        return baseMapper.countVisitByDateRange(startTime, endTime);
    }
}
